/*
 * @(#)ErrorMessage.java 1.0 2005-3-7
 * Copyright 2005 VandaGroup, Inc. All rights reserved.
 */
package com.vanda.util;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
/*******
 * 类说明:
 * 用于VandaException中错误消息处理的辅助类。
 * <P>@author wkf3915
 * <P>@version 1.0 2005-3-7
 */
public class ErrorMessage {
	private static HashMap hmError = null;
	static {
		try {
			ResourceBundle resources =
				ResourceBundle.getBundle("ErrorMessage", Locale.getDefault());
			//Enumeration enum1 = resources.getKeys();
			Enumeration enuKey = resources.getKeys();
			hmError = new HashMap();
			while (enuKey.hasMoreElements()) {
				String strKey = (String) enuKey.nextElement();
				String strValue = resources.getString(strKey);
				int index = strValue.indexOf("#");
				if (index != -1) {
					strValue = strValue.substring(0, index).trim();
				}
				hmError.put(strKey, strValue);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * modify by dougxiao
	 * @param strErrorCode
	 * @return
	 */
	public static String getErrorMessage(String strErrorCode) {
		String strErrorMessage = strErrorCode;
		strErrorMessage = UnicodeToGBK((String) hmError.get(strErrorCode));
		if (strErrorMessage == null || "".equals(strErrorMessage)) {
			strErrorMessage = strErrorCode;
		}
		return strErrorMessage;
	}
	/**
	 * Add by eagle
	 * @param strErrorCode
	 * @param sParams
	 * @return
	 */
	public static String getErrorMessage(
		String strErrorCode,
		String[] sParams) {
		String strErrorMessage = getErrorMessage(strErrorCode);
		StringBuffer sbErrorMsg = new StringBuffer();
		if (strErrorMessage == null) {
			return null;
		}
		StringTokenizer st = new StringTokenizer(strErrorMessage, "?");
		if (sParams == null || st.countTokens() - 1 != sParams.length) {
			return strErrorMessage;
		}
		//将其中的?号替换对应的sParams
		for (int i = 0; i < sParams.length; i++) {
			sbErrorMsg.append(st.nextToken()).append(sParams[i]);
		}
		sbErrorMsg.append(st.nextToken());
		return sbErrorMsg.toString();
	}
	public static String getErrorMessage(String strErrorCode, String sParam) {
		String[] sParams = new String[1];
		sParams[0] = sParam;
		return getErrorMessage(strErrorCode, sParams);
	}
	public static String getErrorMessage(
		String strErrorCode,
		String sParam1,
		String sParam2) {
		String[] sParams = new String[2];
		sParams[0] = sParam1;
		sParams[1] = sParam2;
		return getErrorMessage(strErrorCode, sParams);
	}
	private static String UnicodeToGBK(String s) {
		try {
			if (s == null || s.equals("")) {
				return "";
			}
			String newstring = null;
			newstring = new String(s.getBytes("ISO8859_1"), "GBK");
			return newstring;
		} catch (UnsupportedEncodingException e) {
			return s;
		}
	}
}
